package service

import (
	"afupanel/components/system"
	"afupanel/constant"
	"fmt"
	"strconv"
	"time"
)

type IpLock struct {
	Id         int64
	CreateTime time.Time
	UpdateTime time.Time
	Ip         string
	Count      int    //  计数
	Status     string // LOCK,UNLOCK,PENDING
	Reason     string // 锁定原因
	LockTime   time.Time
	UnlockTime time.Time
}

func GetIp(ip, status string) (has bool, lock IpLock, err error) {
	has, err = Engine.Where("ip = ?", ip).And(" status = ?", status).Get(&lock)
	return
}

func AddBlockIp(ip, reason string) {
	has, lock, err := GetIp(ip, "PENDING")
	if err != nil {
		fmt.Println(err)
		return
	}
	if !has {
		lock := IpLock{
			CreateTime: time.Now(),
			UpdateTime: time.Now(),
			Ip:         ip,
			Count:      1,
			Status:     "PENDING",
			Reason:     reason,
		}
		Engine.InsertOne(&lock)
	} else {
		count := 5
		banDay := 1
		if has, value, err := GetValue(constant.DEFAULT_IP_ERROR_LIMIT); err == nil {
			if has {
				if newInt, err := strconv.Atoi(value); err == nil {
					count = newInt
				}
			}
		}
		if has, value, err := GetValue(constant.DEFAULT_BAN_IP_DAY); err == nil {
			if has {
				if newInt, err := strconv.Atoi(value); err == nil {
					banDay = newInt
				}
			}
		}
		if lock.Count > count {
			//
			var toAdd time.Duration
			if toAdd, err = time.ParseDuration(fmt.Sprintf("%dH", 24*banDay)); err == nil {

			} else {

			}
			now := time.Now()
			endBlockTime := now.Add(toAdd)
			lock.LockTime = now
			lock.UnlockTime = endBlockTime
			lock.Status = "LOCK"
			Engine.ID(lock.Id).Update(lock)
			// 执行Firewalld 将其禁止了
			fd := system.Firewalld{}
			fd.BlockIPs(ip)

		} else {
			lock.Count += 1
			lock.UpdateTime = time.Now()
			Engine.ID(lock.Id).Update(lock)
		}
	}

}
